package com.zonda.sampleretrofit2.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.v4.view.ViewCompat;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.zonda.sampleretrofit2.R;

import java.util.concurrent.atomic.AtomicBoolean;

public final class NewsListItem1Layout extends NewsListItemBaseLayout {

  private final static String LOG_TAG = "NewsListItemLayout";

  private ImageView mRightIv;
  private TextView mTitleTv;
  private NewsListTagView mTagV;

  private String mRightImageUrl;
  private String mTitleText;

  private final AtomicBoolean hasLoadedImage = new AtomicBoolean(false);
  private SimpleTarget<Bitmap> mSimpleTarget;
  private int mRightImageWidth = -1;
  private int mRightImageHeight = -1;

  public NewsListItem1Layout(Context context, AttributeSet attrs) {
    super(context, attrs);
    init();
  }

  private void init() {
    LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
    params.rightMargin = getResources().getDimensionPixelSize(R.dimen.item_left_and_right_padding);
    params.leftMargin = params.rightMargin;
    setLayoutParams(params);
    int topOrBottomPadding = getResources().getDimensionPixelSize(R.dimen.item_top_and_bottom_padding);
    setPadding(0, topOrBottomPadding, 0, topOrBottomPadding);
  }

  @Override
  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    Log.i(LOG_TAG, "-------------" + mTitleTv.getText() + "------------------");

    //控件总宽度
    int widthHint = View.MeasureSpec.getSize(widthMeasureSpec);
    int availableWidth = widthHint - getPaddingLeft() - getPaddingRight();//此处并不需要减去 Margin
    //图片指定宽度
    final int imageWidth = NewsListItemHelper.calculateSmallImageWidth(availableWidth, getResources());
    final int imageHeight = (int) (imageWidth / NewsListItemHelper.SMALL_IMAGE_RATIO);

    mRightImageWidth = imageWidth;
    mRightImageHeight = imageHeight;
    setRightImageUrl(mRightImageUrl);

    int widthUsed = 0;

    if (mRightIv != null && mRightIv.getVisibility() == VISIBLE) {

      LayoutParams rightIvParams = (LayoutParams) mRightIv.getLayoutParams();

      Log.i(LOG_TAG, "onMeasure measureChildWithMargins before mRightIv "
          + "rightIvParams.leftMargin: " + rightIvParams.leftMargin
          + " getMeasuredState: " + ViewCompat.getMeasuredState(mRightIv));

      rightIvParams.width = imageWidth;
      rightIvParams.height = imageHeight;
      rightIvParams.leftMargin = availableWidth - imageWidth;
      measureChildWithMargins(mRightIv, widthMeasureSpec, 0, heightMeasureSpec, 0);

      Log.i(LOG_TAG, "onMeasure measureChildWithMargins after mRightIv "
          + "rightIvParams.leftMargin: " + rightIvParams.leftMargin
          + " getMeasuredState: " + ViewCompat.getMeasuredState(mRightIv));

      widthUsed = imageWidth;
    }

    LayoutParams titleTvParams = (LayoutParams) mTitleTv.getLayoutParams();
    //测量 TitleTv
    measureChildWithMargins(mTitleTv, widthMeasureSpec, widthUsed, heightMeasureSpec, 0);
    measureChildWithMargins(mTagV, widthMeasureSpec, widthUsed, heightMeasureSpec, 0);

    Log.i(LOG_TAG, "onMeasure before titleTvParams.rightMargin: " + titleTvParams.rightMargin
        + " titleTvParams height: " + titleTvParams.height + " mTitleTv.getMeasureHeight(): "
        + mTitleTv.getMeasuredHeight() + " mTitleTv.getMeasuredWidth(): " + mTitleTv.getMeasuredWidth()
        + " mTagV.getMeasuredHeight(): " + mTagV.getMeasuredHeight()
        + " mTagV.getMeasuredHeight(): " + mTagV.getMeasuredWidth()
        + " widthHint: " + widthHint
        + " getPaddingLeft: " + getPaddingLeft());

    int leftHeightHint = mTitleTv.getMeasuredHeight() + mTagV.getMeasuredHeight();
    int heightHint = Math.max(leftHeightHint, imageHeight) + getPaddingTop() + getPaddingBottom();

    if (leftHeightHint < heightHint) {
      titleTvParams.topMargin = (int) ((heightHint - leftHeightHint + 0.5f) / 2) - getPaddingTop();
      LayoutParams tagParams = (LayoutParams) mTagV.getLayoutParams();
      tagParams.topMargin = titleTvParams.topMargin + mTitleTv.getMeasuredHeight();
    }

    widthHint = resolveSize(widthHint, widthMeasureSpec);
    heightHint = resolveSize(heightHint, heightMeasureSpec);
    setMeasuredDimension(widthHint, heightHint);

    Log.i(LOG_TAG, "onMeasure after titleTvParams.rightMargin: " + titleTvParams.rightMargin
        + " titleTvParams height: " + titleTvParams.height + " getMeasureHeight(): "
        + mTitleTv.getMeasuredHeight() + " mTagV.getMeasuredHeight(): " + mTagV.getMeasuredHeight()
        + " mTagV.getMeasuredHeight(): " + mTagV.getMeasuredWidth()
        + " mTitleTv.getMeasuredWidth(): " + mTitleTv.getMeasuredWidth()
        + " widthHint: " + widthHint
        + " getPaddingLeft: " + getPaddingLeft());
  }

  public void setTitleText(String titleText) {
    mTitleText = titleText;
    mTitleTv.setText(titleText);
  }

  public void setRightImageUrl(String rightImageUrl) {

    if (TextUtils.isEmpty(rightImageUrl)) {
      mRightIv.setImageBitmap(null);
      mRightIv.setVisibility(GONE);
      return;
    }

    if (hasLoadedImage.get()
        && TextUtils.equals(rightImageUrl, mRightImageUrl)) {
      return;
    }

    mRightImageUrl = rightImageUrl;
    mRightIv.setVisibility(VISIBLE);

    tryToLoadRightImage();
  }

  private void tryToLoadRightImage() {

    Log.i(LOG_TAG, "tryToLoadRightImage---1");

    if (mRightImageWidth < 0 && mRightImageHeight < 0) {
      return;
    }

    Log.i(LOG_TAG, "tryToLoadRightImage---2");

    if (mSimpleTarget == null) {
      mSimpleTarget = new SimpleTarget<Bitmap>(mRightImageWidth, mRightImageHeight) {
        @Override
        public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
          if (mRightIv != null) {

            Log.i(LOG_TAG, "onResourceReady is in -- mRightIv.getParent().isLayoutRequested: "
                + mRightIv.getParent().isLayoutRequested()
                + " imageWidth: " + mRightImageWidth
                + " resource.getWidth(): " + resource.getWidth()
                + " imageHeight: " + mRightImageHeight
                + " resource.getHeight(): " + resource.getHeight());
            mRightIv.setScaleType(ImageView.ScaleType.FIT_XY);
            mRightIv.setImageBitmap(resource);
            hasLoadedImage.set(true);
          }
        }
      };
    }
    Glide.with(getContext().getApplicationContext()).load(mRightImageUrl).asBitmap().centerCrop().into(mSimpleTarget);
  }

  static void getRightImageMatrix(@NonNull Matrix matrix, int viewWidth, int viewHeight,
                                  @NonNull final Drawable resource) {
    float sx = 1.0f;
    float sy = 1.0f;
    int drawableWidth = resource.getIntrinsicWidth();
    int drawableHeight = resource.getIntrinsicHeight();
    if (viewWidth * viewHeight != 0 && drawableWidth * drawableHeight != 0) {
      float scale = Math.max(viewWidth / (float) drawableWidth, viewHeight / (float) drawableHeight);
      sx = sy = scale;
    }
    matrix.setScale(sx, sy);
  }

  public void setNewsAuthorName(String newsAuthorName) {
    mTagV.setNewsAuthorText(newsAuthorName);
  }

  public void setNewsIssueTime(String newsIssueTime) {
    mTagV.setNewsIssueText(newsIssueTime);
  }

  public void setNewsIconUrl(String newsIconUrl) {
    mTagV.setTagUri(newsIconUrl);
  }

  @Override
  public void freeMemory() {
    super.freeMemory();
  }

  @Override
  public void destroy() {
    super.destroy();
    if (mSimpleTarget != null) {
      Glide.clear(mSimpleTarget);
      mSimpleTarget = null;
    }
    if (mRightIv != null && hasLoadedImage.getAndSet(false)) {
      mRightIv.setImageBitmap(null);
    }
  }

  @Override
  void onInitChildView() {
    if (getChildCount() != 3) {
      return;
    }
    mRightIv = (ImageView) getChildAt(0);
    mTitleTv = (TextView) getChildAt(1);
    mTagV = (NewsListTagView) getChildAt(2);
  }
}
